//
//  UserList.swift
//  CoreDataDemo
//
//  Created by shen on 2023/10/16.
//

import SwiftUI

struct UserListView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(entity: User.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \User.id, ascending: false)], animation: .default)
    // 这就是获取到 coredata user 的数据
    private var userList: FetchedResults<User>

    @State private var showAdd = false

    var body: some View {
        NavigationView {
            VStack {
                if showAdd {
                    addUserView
                }

                if userList.isEmpty {
                    Text("暂无用户数据")
                } else {
                    ForEach(userList, id: \.self) { user in
                        HStack {
                            Text(user.name)
                            Text("爱好: \(user.hobby)")
                        }
                    }
                }
            }
            .padding()
            .navigationTitle("用户列表")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden()
            .navigationBarItems(leading: Button(action: {}, label: {
                Image(systemName: "chevron.left")
            }), trailing: Button(action: {
                self.showAdd = true
            }, label: {
                Image(systemName: "plus")
            }))
        }
    }

    // 表单绑定数据
    @State private var name: String = ""
    @State private var hobby: String = ""

    var addUserView: some View {
        VStack {
            TextField("用户名", text: $name)
                .padding()
                .border(Color.gray)
            TextField("爱好", text: $hobby)
                .padding()
                .border(Color.gray)
            Button(action: {
                addUser()
            }, label: {
                Text("保存")
                    .padding(.horizontal, 2)
                    .padding(.vertical, 15)
                    .frame(maxWidth: .infinity)
                    .background(Color.blue)
                    .foregroundColor(.white).cornerRadius(24)
            })
        }
        .padding()
    }

    func addUser() {
        withAnimation {
            if !name.isEmpty && !hobby.isEmpty {
                let newUser = User(context: viewContext)
                newUser.id = UUID()
                newUser.name = name
                newUser.hobby = hobby

                do {
                    try viewContext.save()
                    showAdd = false
                } catch {
                    let nsError = error as NSError
                    // fatalError() 使应用程序生成崩溃日志并终止。 尽管此功能在开发过程中可能很有用，不应在生产应用程序中使用此功能。
                    fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
                }
            }
        }
    }

    func deleteUser(id: UUID) {
        if let record = userList.first(where: { $0.id == id }) {
            withAnimation {
                viewContext.delete(record)

                do {
                    try viewContext.save()
                } catch {
                    let nsError = error as NSError
                    fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
                }
            }
        }
    }

    func updateUser(id: UUID) {
        if let record = userList.first(where: { $0.id == id }) {
            withAnimation {
                record.name = self.name
                record.hobby = self.hobby

                do {
                    try viewContext.save()
                } catch {
                    let nsError = error as NSError
                    fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
                }
            }
        }
    }
}

#Preview {
    UserListView()
        .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
